package com.tsmti.webservice.custom.standard.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.tsmti.webservice.constants.Constants;
import com.tsmti.webservice.database.DynamicDbDao;
import com.tsmti.webservice.dto.result.DepartmentResultDto;
import com.tsmti.webservice.dto.result.DoctorResultDto;
import com.tsmti.webservice.dto.result.PatientResultDto;
import com.tsmti.webservice.util.Config;
import com.tsmti.webservice.util.ConvertUtil;
import com.tsmti.webservice.util.DynamicDbUtils;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.lang.StringUtils;
import org.springframework.jdbc.core.RowMapper;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Package：com.tsmti.webservice.custom.standard.impl
 * @Class：HisImpl
 * @Description： HIS系统接口
 * @Author：king
 * @Date：Created in 2018/11/15 15:21
 * @Company:
 * @Version：
 * @Modified By:
 */
public class HisImpl {
    private  static DynamicDbDao jdbcHis = DynamicDbUtils.getDynamicDbDao(Constants.DB_HIS);

    /**
     * 获取病人信息列表
     * @param orgId 医院代码
     * @param type 病人类型
     * @param patientId 病案号
     * @param patientNo 门诊/住院号
     * @param inPatientId 就诊ID
     * @param inPatientNo 就诊序号
     * @return 获取病人信息列表
     */
    public List<PatientResultDto> getHisPatientById(String orgId,String type, String patientId, String patientNo, String inPatientId,String inPatientNo) {
        List<PatientResultDto> patientResultDtoList = new ArrayList<>();
        if(StringUtils.isNotEmpty(type)){
            if(Constants.PatientType.OUT.equals(type)){
                patientResultDtoList = getHisOutPatient(patientId,patientNo, inPatientId,inPatientNo);
            }else if(Constants.PatientType.IN.equals(type)){
                patientResultDtoList = getHisInPatient(patientId,patientNo, inPatientId,inPatientNo);
            }else if(Constants.PatientType.PE.equals(type)){

            }
        }else {
            patientResultDtoList = getHisInPatient(patientId,patientNo, inPatientId,inPatientNo);
            List<PatientResultDto> patientResultDtoListOut = getHisOutPatient(patientId,patientNo, inPatientId,inPatientNo);
            patientResultDtoList.addAll(patientResultDtoListOut);
        }
        return patientResultDtoList;
    }



    /**
     * 获取病区、科室所有在院病人信息
     * @param orgId
     * @param patientType
     * @param patientWard
     * @return
     */
    public List<PatientResultDto> getHisPatientByWard(String orgId, String patientType, String patientWard) {
        List<PatientResultDto> patientInfoList = new ArrayList<>();
        if(StringUtils.isNotEmpty(patientType)){
            if(Constants.PatientType.OUT.equals(patientType)){
                patientInfoList = getHisOutPatientList(orgId,patientWard);
            }else if(Constants.PatientType.IN.equals(patientType)){
                patientInfoList = getHisInPatientByWardCode(orgId,patientWard);
            }else if(Constants.PatientType.PE.equals(patientType)){

            }
        }
        return patientInfoList;
    }

    /**
     * 获取病区列表
     * @return
     */
    public List<DepartmentResultDto> getWardList() {
        return null;
    }

    /**
     * 获取医生信息列表
     * @param orgId
     * @param doctorCode
     * @return
     */
    public List<DoctorResultDto> getDoctorList(String orgId, String doctorCode){

        List<DoctorResultDto> list = new ArrayList<DoctorResultDto>();
        try {
            //if(1==1)throw new Exception("错误");
            String url = Config.getString("hrWebService","");
            HttpClient httpClient = new HttpClient();
            httpClient.getHostConfiguration().setHost(url);
            PostMethod method = new PostMethod(url);

            JSONObject queryParam = new JSONObject();
            JSONObject args = new JSONObject();

            args.put("hosCode", "000000");
            args.put("orgCode", "000000");
            args.put("doctCode", doctorCode);

            queryParam.put("args",args);
            queryParam.put("captcha","token");
            queryParam.put("funcode","SX_0001");

            RequestEntity requestEntity = new StringRequestEntity(queryParam.toString(), "application/json", "utf-8");
            System.out.println(queryParam.toString());
            method.setRequestEntity(requestEntity);
            method.releaseConnection();
            method.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
            httpClient.executeMethod(method);
            String msgInfo = method.getResponseBodyAsString();
            JSONObject obj = JSON.parseObject(msgInfo);
            if (obj.getIntValue(Constants.CODE) == 0) {
                JSONArray arrDoctor = obj.getJSONArray("doctList");
                if(arrDoctor != null && arrDoctor.size() > 0) {
                    for (int i = 0; i < arrDoctor.size(); i++) {
                        JSONObject doctor = arrDoctor.getJSONObject(i);
                        if (StringUtils.isEmpty(ConvertUtil.null2String(doctor.getString("doctCode")))) {
                            continue;
                        }
                        DoctorResultDto doctorDto = new DoctorResultDto();
                  /*  String doctProfe = ConvertUtil.null2String(doctor.getString("doctProfe"));*/
                        String doctTechnicalPosition1 = ConvertUtil.null2String(doctor.getString("doctTechnicalPosition1"));
                        String doctTechnicalPosition2 = ConvertUtil.null2String(doctor.getString("doctTechnicalPosition2"));
                        int doctorLevel = 0;

                        if ("住院医师".equals(doctTechnicalPosition1) || "住院医师".equals(doctTechnicalPosition2)) {
                            doctorLevel = 0;
                        } else if ("主治医师".equals(doctTechnicalPosition1) || "主治医师".equals(doctTechnicalPosition2)) {
                            doctorLevel = 2;
                        } else if ("副主任医师".equals(doctTechnicalPosition1) || "副主任医师".equals(doctTechnicalPosition2)) {
                            doctorLevel = 3;
                        } else if ("主任医师".equals(doctTechnicalPosition1) || "主任医师".equals(doctTechnicalPosition2)) {
                            doctorLevel = 4;
                        } else {
                            doctorLevel = 0;
                        }
                        ;

                        doctorDto.setDoctProfe(ConvertUtil.null2String(doctorLevel));
                        doctorDto.setDoctorCode(ConvertUtil.null2String(doctor.getString("doctCode")));
                        doctorDto.setDoctorId(ConvertUtil.null2String(doctor.getString("doctCode")));
                        doctorDto.setName(ConvertUtil.null2String(doctor.getString("doctName")));
                        doctorDto.setTellphone(ConvertUtil.null2String(doctor.getString("doctPhone")));
                        String doctPhoneDH = ConvertUtil.null2String(doctor.getString("doctPhoneDH"));
                        if (StringUtils.isEmpty(doctPhoneDH) || !ConvertUtil.isNumeric(doctPhoneDH)) {
                            doctPhoneDH = ConvertUtil.null2String(doctor.getString("doctPhone"));
                        }
                        doctorDto.setShortPhone(doctPhoneDH);
                        doctorDto.setPyCode(ConvertUtil.null2String(doctor.getString("doctPinYinName")));
                        doctorDto.setDeptName(ConvertUtil.null2String(doctor.getString("doctDeptName")));
                        doctorDto.setDeptCode(ConvertUtil.null2String(doctor.getString("doctDeptCode")));
                        list.add(doctorDto);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }

    /***
     * 获取某病区住院病人信息
     * @param wardCode
     * @return
     */
    private List<PatientResultDto> getHisInPatientByWardCode(String orgId,String wardCode) {
        StringBuffer sql = new StringBuffer("select * from V_HSBBI_RECORDHOME where  BRZYZT = 2 ");
        if (StringUtils.isNotEmpty(wardCode)) {
            sql.append(" and zybqid = '" + wardCode + "' ");
        }
        sql.append(" order by brryrq desc,brzyid desc");
        List<PatientResultDto> patientInfoList = jdbcHis.query(sql.toString(),
                new RowMapper<PatientResultDto>() {
                    @Override
                    public PatientResultDto mapRow(ResultSet rs, int rowNum) throws SQLException {
                        return getPatientInDto(rs);
                    }
                });
        return patientInfoList;
    }

    /***
     * 获取门诊病人信息列表
     * @param wardCode
     * @return
     */
    private List<PatientResultDto> getHisOutPatientList(String orgId,String wardCode) {
        StringBuffer sql = new StringBuffer("select * from V_HSBCI_TREATINFO where 1=1 ");
        if (!StringUtils.isEmpty(wardCode)) {
            sql.append(" and jzksid='" + wardCode + "' ");
        }
        sql.append(" order by BRJZRQ desc, BRJZID desc,BRDABH desc");
        System.out.println(sql.toString());
        List<PatientResultDto> patientInfoList = jdbcHis.query(sql.toString(),
                new RowMapper<PatientResultDto>() {
                    @Override
                    public PatientResultDto mapRow(ResultSet rs, int rowNum) throws SQLException {
                        return getPatientOutDto(rs);
                    }
                });
        return patientInfoList;
    }

    /***
     * 获取住院病人信息
     * @param patientId
     * @param patientNo
     * @param inPatientId 就诊ID
     * @param inPatientNo 就诊序号
     * @return 获取住院病人信息
     */
    private List<PatientResultDto> getHisInPatient(String patientId, String patientNo,String inPatientId,String inPatientNo) {
        StringBuffer sql = new StringBuffer("select * from V_HSBBI_RECORDHOME where 1 = 1 ");
        if (StringUtils.isNotEmpty(patientId)) {
            sql.append(" and BRDABH = '" + patientId + "' ");
        }
        if (StringUtils.isNotEmpty(patientNo)) {
            sql.append(" and BRJZHM = '" + patientNo + "' ");
        }
        if (StringUtils.isNotEmpty(inPatientId)) {
            sql.append(" and BRJZID = '" + inPatientId + "' ");
        }
        if (StringUtils.isNotEmpty(inPatientNo)) {
            sql.append(" and BRZYID = '" + inPatientNo + "' ");
        }
        sql.append("  and BRZYZT = 2 order by brryrq desc,brzyid desc");

        System.out.println(sql.toString());

        List<PatientResultDto> patientInfoList = jdbcHis.query(sql.toString(),
                new RowMapper<PatientResultDto>() {
                    @Override
                    public PatientResultDto mapRow(ResultSet rs, int rowNum) throws SQLException {
                        return getPatientInDto(rs);
                    }
                });
        return patientInfoList;
    }

    /***
     * 获取门诊病人信息
     * @param patientId 病案号
     * @param patientNo 门诊/住院号
     * @param inPatientId 就诊ID
     * @param inPatientNo 就诊序号
     * @return 获取门诊病人信息
     */
    private List<PatientResultDto> getHisOutPatient(String patientId,String patientNo,String inPatientId,String inPatientNo) {
        StringBuffer sql = new StringBuffer("select * from V_HSBCI_TREATINFO where 1= 1 ");
        if (StringUtils.isNotEmpty(patientId)) {
            sql.append(" and  BRDABH = '" + patientId + "'");
        }
        if (StringUtils.isNotEmpty(patientNo)) {
            sql.append(" and  BRJZHM = '" + patientNo + "' ");
        }
        if (StringUtils.isNotEmpty(inPatientId)) {
            sql.append(" and  BRJZID = '" + inPatientId + "' ");
        }
        if (StringUtils.isNotEmpty(inPatientNo)) {
            sql.append(" and   = '" + inPatientNo + "' ");
        }
        sql.append(" order by BRJZRQ desc, BRJZID desc,BRDABH desc");
        System.out.println(sql.toString());

        List<PatientResultDto> patientInfoList = jdbcHis.query(sql.toString(),
                new RowMapper<PatientResultDto>() {
                    @Override
                    public PatientResultDto mapRow(ResultSet rs, int rowNum) throws SQLException {
                        return getPatientOutDto(rs);
                    }
                });
        return patientInfoList;
    }




    private String matchResult(int type, String str)
    {
        String regEx1 = "[\\u4e00-\\u9fa5]";
        String regEx2 = "[a-z||A-Z]";
        String regEx3 = "[0-9]";
        Pattern p = null;
        if(type==1){
            p = Pattern.compile(regEx1);
        }else {
            p = Pattern.compile(regEx3);
        }
        StringBuilder sb = new StringBuilder();
        Matcher m = p.matcher(str);
        while (m.find()) {
            for (int i = 0; i <= m.groupCount(); i++) {
                sb.append(m.group());
            }
        }
        return sb.toString();
    }

    /**
     * 病人类型
     * @param type 类型名称
     * @return 病人类型
     */
    private String getPatientType(String type){
        Map<String,String> map = new HashMap<>(16);
        map.put("2","1");
        map.put("1","2");
        map.put("3","3");
        if(map.containsKey(type)){
            return map.get(type);
        }
        return "1";
    }

    /**
     * 性别改成 value
     * @param sexName 性别中文
     * @return 性别改成 value
     */
    private String getSex(String sexName){
        if(Constants.MAN.equals(sexName)){
            return "1";
        }else if(Constants.WOMEN.equals(sexName)){
            return "2";
        }else {
            return "3";
        }
    }

    /**
     * 组装住院病人信息
     * @param rs 结果resultSet
     * @return 组装住院病人信息
     */
    private PatientResultDto  getPatientInDto(ResultSet rs) throws SQLException {
        PatientResultDto info = new PatientResultDto();
        info.setPatientId(ConvertUtil.null2String(rs.getString("BRDABH")));
        info.setPatientNo(ConvertUtil.null2String(rs.getString("BRJZHM")));
        info.setInPatientId(ConvertUtil.null2String(rs.getString("BRJZID")));
        info.setInPatientNo(ConvertUtil.null2String(rs.getString("BRZYID")));
        //住院
        info.setPatientType("2");
        info.setPatientName(ConvertUtil.null2String(rs.getString("BRDAXM")));
        info.setPatientSex(ConvertUtil.null2String(rs.getString("BRDAXB")));
        info.setPatientAge(ConvertUtil.null2String(rs.getString("BRJZNL")));
        info.setPatageType(ConvertUtil.null2String(rs.getString("BRNLDW")));
        info.setPatIdCard(ConvertUtil.null2String(rs.getString("BRSFZH")));
        info.setDeptCode(ConvertUtil.null2String(rs.getString("ZYKSID")));
        info.setWardCode(ConvertUtil.null2String(rs.getString("ZYBQID")));
        info.setDoctorId(ConvertUtil.null2String(rs.getString("ZZYSID")));
        info.setBirthday(ConvertUtil.null2String(rs.getString("BRCSRQ")));
        info.setPhone(ConvertUtil.null2String(rs.getString("BRLXDH")));
        info.setAddress(ConvertUtil.null2String(rs.getString("BRJTDZ")));
        info.setDiagnosis(ConvertUtil.null2String(rs.getString("RYZDMC")));
        info.setCompany(ConvertUtil.null2String(rs.getString("BRDWMC")));
        return info;
    }

    /**
     * 组装门诊病人信息
     * @param rs 结果resultSet
     * @return  组装门诊病人信息
     */
    private PatientResultDto getPatientOutDto(ResultSet rs) throws SQLException{
        PatientResultDto info = new PatientResultDto();
        info.setPatientId(ConvertUtil.null2String(rs.getString("BRDABH")));
        info.setPatientNo(ConvertUtil.null2String(rs.getString("BRJZHM")));
        info.setInPatientId(ConvertUtil.null2String(rs.getString("BRJZID")));
        info.setInPatientNo(ConvertUtil.null2String(rs.getString("BRJZXH")));
        info.setPatientType("1");
        info.setPatientName(ConvertUtil.null2String(rs.getString("BRDAXM")));
        info.setPatientSex(ConvertUtil.null2String(rs.getString("BRDAXB")));
        info.setPatientAge(ConvertUtil.null2String(matchResult(2,ConvertUtil.null2String(rs.getString("BRJZNL")))));
        info.setPatageType(ConvertUtil.null2String(matchResult(1,ConvertUtil.null2String(rs.getString("BRJZNL")))));
        info.setPatIdCard(ConvertUtil.null2String(rs.getString("BRSFZH")));
        info.setDeptCode(ConvertUtil.null2String(rs.getString("JZKSID")));
        info.setDoctorId(ConvertUtil.null2String(rs.getString("JZYSID")));
        info.setBirthday(ConvertUtil.null2String(rs.getString("BRCSRQ")));
        info.setPhone(ConvertUtil.null2String(rs.getString("BRLXDH")));
        info.setAddress(ConvertUtil.null2String(rs.getString("BRJTDZ")));
        info.setDiagnosis(ConvertUtil.null2String(rs.getString("LCZDMC")));
        info.setCompany(ConvertUtil.null2String(rs.getString("BRDWMC")));
        info.setPatientReadMe(ConvertUtil.null2String(rs.getString("BRZSNR")));
        info.setPatientHpi(ConvertUtil.null2String(rs.getString("BRXBS")));
        info.setBadHistory(ConvertUtil.null2String(rs.getString("BRGRS")));
        info.setPastHistory(ConvertUtil.null2String(rs.getString("BRJWS")));
        info.setPatientPE(ConvertUtil.null2String(rs.getString("BRTGJC")));
        info.setMedicalAdvice(ConvertUtil.null2String(rs.getString("TSCLYJ")));
        return info;
    }
}
